package com.ruoyi.web.controller.example;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.BizException;
import com.ruoyi.resturant.domain.ResShop;
import com.ruoyi.resturant.service.IResShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Anonymous
@Api(tags="Redis测试")
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private IResShopService resShopService;
    @Autowired
    private RedisCache redisCache;
    @ApiOperation("存储Redis数据")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public AjaxResult setRedisObj(@PathVariable("id") Long id){
      ResShop resShop= resShopService.selectResShopById(id);
        if(resShop == null) {
            throw new BizException(404, "店铺id(" + id + ")不存在");
        }
       String str = JSON.toJSONString(resShop);
       redisCache.setCacheObject(String.valueOf(id),str,1, TimeUnit.HOURS);
       return AjaxResult.success(resShop);
    }
    @ApiOperation("取Redis数据")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/ids/{id}")
    public AjaxResult getRedisObj(@PathVariable("id") Long id){
       String str =  redisCache.getCacheObject(String.valueOf(id));
        ResShop resShop = JSON.parseObject(str, ResShop.class);
        return AjaxResult.success(resShop);
    }
}
